<script lang="ts" setup>
import { throttle } from "lodash-es";
import { getImg } from "@/utils";

const emits = defineEmits<{
  (e: "play"): void;
}>();
// 定时器 ID，用于控制显示/隐藏动画
const timerId = ref<any>(null);
// 控制组件是否可见
const isVisible = ref(true);
// 记录上一次滚动位置
const lastScrollTop = ref(0);
const onScroll = throttle(() => {
  // 获取当前滚动位置
  const scrollTop = window.scrollY;
  // 计算与上次滚动位置的差值
  const compareLast = scrollTop - lastScrollTop.value;
  // 向下滚动时隐藏组件
  if (compareLast > 0) {
    isVisible.value = false;
    clearTimeout(timerId.value);
    timerId.value = setTimeout(() => {
      isVisible.value = true;
    }, 300);
  } else {
    // 向上滚动时显示组件
    isVisible.value = true;
  }
  // 更新上次滚动位置
  lastScrollTop.value = scrollTop;
}, 50);
onMounted(() => {
  setTimeout(() => {
    window.addEventListener("scroll", onScroll);
  }, 100);
});
onBeforeUnmount(() => {
  window.removeEventListener("scroll", onScroll);
});

const play = () => {
  emits("play");
};
</script>
<template>
  <div
    @click="play"
    :class="[
      'w-186 mx-auto transition-bottom py-8 rounded-46 flex-center gap-x-8 bg-[#f9ca24] sticky mb-32',
      !isVisible ? 'bottom-[-78px]' : 'bottom-32',
    ]"
  >
    <img class="w-32 h-28" :src="getImg('zy_play.png')" alt="" />
    <span class="font-bold text-16 color-[#000] lh-20">Play Random</span>
  </div>
</template>
